package top.songxs.gmall.rabbit.service.impl;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import top.songxs.gmall.rabbit.constant.MqConstant;
import top.songxs.gmall.rabbit.service.RabbitMqBizService;

import java.io.IOException;

@Component
@Slf4j
public class RabbitMqBizServiceImpl implements RabbitMqBizService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void retry(Message message, Channel channel, int count) {
        String MD5Id = DigestUtils.md5DigestAsHex(message.getBody());
        Long resultCount = redisTemplate.opsForValue().increment(MqConstant.REDIS_MSG_RETRY_COUNT + MD5Id);

        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        if (resultCount <= count) {

            // 进行重试
            try {
                log.error("消息处理失败了，进行重试..." + count);
                channel.basicNack(deliveryTag , false , true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            //不再进行重试
            //TODO:将消息持久化到数据库中后续人工处理
            try {
                log.error("重试次数已经到达上限了" + count);
                channel.basicNack(deliveryTag,false,false);

                // 删除Redis中的count计数器
                redisTemplate.delete(MqConstant.REDIS_MSG_RETRY_COUNT + MD5Id) ;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


    }
}
